import { addOrEdit, findCacheCarts,findPageCarts } from "@/api/cart";
import {findPage} from '@/api/address';
import {addOrder} from '@/api/order'
import {userBehaviors} from '@/behaviors/userBehaviors';
import {orderBehaviors} from '@/behaviors/orderBehaviors'
import {msgTip} from '@/utils/MsgTipApi'

Page({
  behaviors:[userBehaviors,orderBehaviors],
  /**
   * 页面的初始数据
   */
  data: {
    // 预支付界面订单信息
    goodsInfo:[],
    totalPrice:0,
    show:false,
    defaultAddress:{},
    address:[],
    message:''
  },

  formParams(){
    let paramsItem = []
    this.data.goodsInfo.forEach(item=>{
      let e = {
        cartId:item.id,goodName:item.goodName,goodPrice:item.goodPrice,totalPrice:item.goodPrice * item.count,goodId:item.goodId,count:item.count
      }
      paramsItem.push(e)
    })
    return {
      recevingId:this.data.defaultAddress.id,
      recevindName:this.data.defaultAddress.userName,
      recevingPhone:this.data.defaultAddress.phone,
      recevingAddress:this.data.defaultAddress.fullAddress,
      message:this.data.message,
      orderItems: paramsItem,
      totalPrice: this.data.totalPrice
    }
  },

  /**
   * 提交订单
   */
  async onSubmit(){
    let params = this.formParams();
    params['orderStatus'] = 1
    let returnData = await addOrder(params)
    this.data.goodsInfo = []
    if(returnData){
      wx.navigateTo({
        url: '/modules/orderModules/pages/orderPay/index',
      })
    }
  },
  /**
   *切换地址
   */
  selectAddress(){
    this.updateGoodsStoreMessage(this.data.message)
    this.updateDefaultStoreAddress(this.data.defaultAddress)
    wx.navigateTo({
      url: '/modules/orderModules/pages/orderAddress/index',
    })
  },

  /**
   * 更新购买数量
   */
  async onChangeStep(event){
    let count = event.detail;
    let {index,goodid,id} = event.currentTarget.dataset;
    let curGood = this.data.goodsInfo[index];
    let diffPrice = (curGood.count - count) * curGood.goodPrice
    let diffCount = count - curGood.count;
    this.setData({
      [`goodsInfo[${index}].count`]:  count,
      totalPrice: this.data.totalPrice - diffPrice
    })
    let params = {id,count:diffCount,goodId:goodid}
    await addOrEdit(params)
  },
  /**
   * 
   * @param {加载商品信息} options 
   */
  async findCacheCarts(){
    let data = await findCacheCarts();
    let allPrice = 0;
    data.forEach(item =>{
      allPrice += item.count * item.goodPrice
      item.goodPrice = item.goodPrice.toFixed(2)
    })
    this.setData({
      goodsInfo:data,
      totalPrice: allPrice
    })
  },
  /**
   * 加载地址信息
   */
  async findPageAddress(){
    let addressReqData = {pageIndex:1,pageSize:50}
    let data = await findPage(addressReqData);
    this.setData({
      address: data.records
    })
    data.records.forEach(item =>{
      if(item.isDefault){
        this.setData({defaultAddress:item})
        return;
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // 如果是从购物车中取的数据
    if(Object.keys(options).length == 0){
      this.findCacheCarts()
    }else{
      // 如果是直接从商品页面跳转的购买
      let data =[]
      data.push(options)
      console.log(this.data.goodsInfo);
      this.setData({
        goodsInfo:data,
        totalPrice:options.count * options.goodPrice
      })
    }
    this.setData({
      message:Object.keys(this.data.goodsStoreMessage).length == 0 ? '' : this.data.goodsStoreMessage
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(Object.keys(this.data.defaultStoreAddress).length == 0){
      this.findPageAddress()
    }else{
      this.setData({
        defaultAddress:this.data.defaultStoreAddress
      })
    }
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  async onUnload() {
    if(this.data.goodsInfo.length > 0){
      let params = this.formParams();
      console.log(params,params['orderItems']);
      params['orderStatus'] = 0;
      let returnFlag = await addOrder(params)
      returnFlag ? msgTip({title:"订单已经加入，请及时支付"}) : msgTip({title:"订单保存异常，请检查"})
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})